package com.gaokuo.es.property;

import java.beans.Introspector;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 根据函数获取字段名称
 * @author gaokuo 网络
 * @date 2021-04-22
 */
public class FuncFieldNameUtil {


    public static <T, R>  String get(PropertyFunc<T, R> func) {
        // 从function取出序列化方法
        Method writeReplaceMethod;
        try {
            writeReplaceMethod = func.getClass().getDeclaredMethod("writeReplace");
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 从序列化方法取出序列化的lambda信息
        boolean isAccessible = writeReplaceMethod.isAccessible();
        writeReplaceMethod.setAccessible(true);
        SerializedLambda serializedLambda;
        try {
            serializedLambda = (SerializedLambda) writeReplaceMethod.invoke(func);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
        writeReplaceMethod.setAccessible(isAccessible);
        // 从lambda信息取出method、field、class等
        String fieldName = serializedLambda.getImplMethodName();
        fieldName = Introspector.decapitalize(fieldName.replace("get", ""));
        return fieldName;
    }

}